package com.weiweiqin.controller.home;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.weiweiqin.model.*;
import com.weiweiqin.service.*;
import com.weiweiqin.utils.BigDemicalUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.weiweiqin.constants.Constants;
import com.weiweiqin.vo.common.CartVO;
import com.weiweiqin.vo.common.OrderQueryVO;
import com.weiweiqin.vo.common.OrderTabVO;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;

@Controller
@RequestMapping("front/order")
public class FOrderController {

	private static final Logger logger = LoggerFactory
			.getLogger(FOrderController.class);
	@Autowired
	private OrderService orderService;
	@Autowired
	private GoodsService goodsService;

	@Autowired
	private CustomerService customerService;
	@Autowired
	private ColorSizeItemService colorSizeItemService;

	@Autowired
	private PrizeService prizeService;

	@Autowired
	private IpLimitService ipLimitService;
	
	private static String getHeader(HttpServletRequest request, String headName) {
        String value = request.getHeader(headName);
        return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
    }

	@RequestMapping(value = "/addByPrize.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String addByPrize(Order order, Integer itemId,String color,int num,String size,String pic,int goodsId,int prizeId,HttpServletRequest request,
			HttpSession session) {
		logger.info("Enter method add....，order=" + order);
		Result result = new Result();
		// 设置顾客信息
		Customer customer = (Customer) session.getAttribute("customer");
		Prize prize = prizeService.get(prizeId);
		//验证是否存在该奖品或是否为该用户的奖品或该奖品已经使用
		if(null == prize || prize.getCustomerId() != customer.getId() || prize.getStatus() == 2){
			result.setResult(false);
			result.setErrorMsg("您无法领取该商品！");
			return result.toJson();
		}
		order.setPayType(1);
		order.setCustomerId(customer.getId());
		CartVO cartVO = new CartVO();
		cartVO.setColor(color);
		cartVO.setNum(num);
		cartVO.setItemId(itemId);
		cartVO.setSize(size);
		cartVO.setPic(pic);
		cartVO.setGoodsId(goodsId);
		Goods goods = goodsService.get(goodsId);
		ColorSizeItem colorSizeItem = colorSizeItemService.get(itemId);
		cartVO.setColorSizeItem(colorSizeItem);

		cartVO.setGoods(goods);
		String ipFromNginx = getHeader(request, "X-Real-IP");
		String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
		logger.info("ip=" + ip);

		// 保存订单信息
		try {
			List<CartVO> goodsList = new ArrayList<CartVO>();
            goodsList.add(cartVO);
			//后台重新计算订单总价格
			double totalPrice = 0;
            totalPrice = totalPrice + cartVO.getColorSizeItem().getPrice()*cartVO.getNum();
            order.setTotalPrice(new BigDecimal(totalPrice));
			//设置用户IP
			order.setIp(ip);
			orderService.saveByPrize(order, goodsList,prize);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

	@RequestMapping(value = "/addByJF.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String addByJF(Order order, Integer itemId,String color,int num,String size,String pic,int goodsId,HttpServletRequest request,
			HttpSession session) {
		logger.info("Enter method add....，order=" + order);
		Result result = new Result();
		// 设置顾客信息
		Customer customer = (Customer) session.getAttribute("customer");
		order.setPayType(0);
		order.setCustomerId(customer.getId());
		CartVO cartVO = new CartVO();
		cartVO.setColor(color);
		cartVO.setNum(num);
		cartVO.setItemId(itemId);
		cartVO.setSize(size);
		cartVO.setPic(pic);
		cartVO.setGoodsId(goodsId);
		Goods goods = goodsService.get(goodsId);
		//后台验证积分是否充足
		Customer customer1 = customerService.get(customer.getId());
		if(customer1.getIntegral() <goods.getIntegral()){
			result.setResult(false);
			result.setErrorMsg("您的积分不足，无法兑换该商品！");
			return result.toJson();
		}else{
			customer1.setIntegral(customer1.getIntegral()-goods.getIntegral());
		}
		ColorSizeItem colorSizeItem = colorSizeItemService.get(itemId);
		cartVO.setColorSizeItem(colorSizeItem);

		cartVO.setGoods(goods);
		String ipFromNginx = getHeader(request, "X-Real-IP");
		String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
		logger.info("ip=" + ip);

		// 保存订单信息
		try {
			List<CartVO> goodsList = new ArrayList<CartVO>();
            goodsList.add(cartVO);
			//后台重新计算订单总价格
			double totalPrice = 0;
            totalPrice = totalPrice + cartVO.getColorSizeItem().getPrice()*cartVO.getNum();
            order.setTotalPrice(new BigDecimal(totalPrice));
			//设置用户IP
			order.setIp(ip);
			orderService.saveByJF(order, goodsList,customer1);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

	@RequestMapping(value = "/add.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String add(Order order, Integer itemId,String color,int num,String size,String pic,int goodsId,HttpServletRequest request,
							 HttpSession session) {
		logger.info("Enter method add....，order=" + order);
		Result result = new Result();
		// 设置顾客信息
		Customer customer = (Customer) session.getAttribute("customer");
		order.setCustomerId(customer.getId());
		CartVO cartVO = new CartVO();
		cartVO.setColor(color);
		cartVO.setNum(num);
		cartVO.setItemId(itemId);
		cartVO.setSize(size);
		cartVO.setPic(pic);
		cartVO.setGoodsId(goodsId);
		Goods goods = goodsService.get(goodsId);
		ColorSizeItem colorSizeItem = colorSizeItemService.get(itemId);
		cartVO.setColorSizeItem(colorSizeItem);

		cartVO.setGoods(goods);
		String ipFromNginx = getHeader(request, "X-Real-IP");
		String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
		logger.info("ip=" + ip);

		// 保存订单信息
		try {
			List<CartVO> goodsList = new ArrayList<CartVO>();
			goodsList.add(cartVO);
			//后台重新计算订单总价格
			double totalPrice = 0;
			totalPrice = totalPrice + cartVO.getColorSizeItem().getPrice()*cartVO.getNum();
			order.setTotalPrice(new BigDecimal(totalPrice));
			//设置用户IP
			order.setIp(ip);
			orderService.save(order, goodsList);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		result.setResult(true);
		result.setObj(order);
		return result.toJson();
	}

    @RequestMapping(value = "/addByCart.do", method = { RequestMethod.POST,
            RequestMethod.GET })
    @ResponseBody
    public String addByCart(Order order, String keys,HttpServletRequest request,
                      HttpSession session) {
        logger.info("Enter method add....，order=" + order);

        String ipFromNginx = getHeader(request, "X-Real-IP");

        String ip = StringUtils.isEmpty(ipFromNginx) ? request.getRemoteAddr() : ipFromNginx;
        logger.info("ip=" + ip);
        Result result = new Result();
        // 设置顾客信息
        if (null != session.getAttribute("customer")) {
            Customer customer = (Customer) session.getAttribute("customer");
            order.setCustomerId(customer.getId());
        }else {
            result.setResult(false);
            result.setErrorMsg("登录超时，请重新链接首页购买！");
            return result.toJson();
        }

        // 保存订单信息
        try {
			Map<String, Object> mp = getCartsByKeys(session,keys);
			Double totalPrice = (Double)mp.get("totalPrice");
			order.setTotalPrice(new BigDecimal(totalPrice));
			List<CartVO> goodsList = (List<CartVO>)mp.get("cartList");
			Map<String, CartVO> surPluscartList = (Map<String, CartVO>)mp.get("surPluscarts");
            if (null == goodsList || goodsList.isEmpty()) {
                result.setResult(false);
                result.setErrorMsg("您的购物车没有商品或商品已经过期，请刷新页面重新购买！");
                return result.toJson();
            }
            //设置用户IP
            order.setIp(ip);
            orderService.save(order, goodsList);
            // 重置购物车
			if(surPluscartList.size() ==0) {
				session.setAttribute("carts", null);
			} else {
				session.setAttribute("carts", surPluscartList);
			}
        } catch (Exception e) {
            logger.error("保存订单失败...", e);
            result.setResult(false);
            result.setErrorMsg("系统繁忙，请您稍后再试！");
            return result.toJson();
        }
        // 采用支付宝担保交易付款
//        if (Constants.Order.PAY_ZHIFUBAO == order.getPayType()) {
//            return sendZhifubao(order, request);
//        }
        result.setResult(true);
        result.setObj(order);
        return result.toJson();
    }
	
	@RequestMapping(value = "/addDpShop.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String addDpShop(Order order, String province, String city, String area,
			String street,String color,String size,int goodsId,int num,HttpServletRequest request, HttpSession session) {
		logger.info("Enter method add....，order=" + order + ",province="
				+ province + ",city=" + city + ",area=" + area + ",street="
				+ street+",goodsId="+goodsId);
		String ip = request.getRemoteAddr();
		order.setIp(ip);
		logger.info("ip=" + ip);
		Result result = new Result();
		try {
			//防止空地址提交
			if(StringUtils.isEmpty(province) || StringUtils.isEmpty(city) || StringUtils.isEmpty(area) || StringUtils.isEmpty(street) || StringUtils.isEmpty(order.getMobile()) || StringUtils.isEmpty(order.getName())){
				result.setResult(false);
				return result.toJson();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			Map<String,Object> conditions = new HashMap<String, Object>();
			conditions.put("addDate",date);
			if(!StringUtils.isEmpty(province)){
				if(province.indexOf("|") != -1){
					province = province.split("\\|")[1];
				}
			}
			
			if(!StringUtils.isEmpty(city)){
				if(city.indexOf("|") != -1){
					city = city.split("\\|")[1];
				}
			}
			
			if(!StringUtils.isEmpty(area)){
				if(area.indexOf("|") != -1){
					area = area.split("\\|")[1];
				}
			}
			String info = order.getInfo();
			info = info+","+color+","+size;
			order.setInfo(info);
			orderService.addDpShop(order, province, city, area, street,goodsId,num,color,size,conditions);
			// 清空session验证码
			session.setAttribute("mobileValidateCode", null);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		logger.info("End method add....");
		result.setResult(true);
		return result.toJson();
	}
	
	@RequestMapping(value = "/addDp.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String addDp(Order order, String province, String city, String area,
			String street,String color,String size,HttpServletRequest request, HttpSession session) {
		logger.info("Enter method add....，order=" + order + ",province="
				+ province + ",city=" + city + ",area=" + area + ",street="
				+ street);
		String ip = request.getRemoteAddr();
		order.setIp(ip);
		logger.info("ip=" + ip);
		Result result = new Result();
		try {
			//防止空地址提交
			if(StringUtils.isEmpty(province) || StringUtils.isEmpty(city) || StringUtils.isEmpty(area) || StringUtils.isEmpty(street) || StringUtils.isEmpty(order.getMobile()) || StringUtils.isEmpty(order.getName())){
				result.setResult(false);
				return result.toJson();
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			Map<String,Object> conditions = new HashMap<String, Object>();
			conditions.put("addDate",date);
			if(!StringUtils.isEmpty(province)){
				if(province.indexOf("|") != -1){
					province = province.split("\\|")[1];
				}
			}
			
			if(!StringUtils.isEmpty(city)){
				if(city.indexOf("|") != -1){
					city = city.split("\\|")[1];
				}
			}
			
			if(!StringUtils.isEmpty(area)){
				if(area.indexOf("|") != -1){
					area = area.split("\\|")[1];
				}
			}
			String info = order.getInfo();
			info = info+","+color+","+size;
			order.setInfo(info);
			orderService.addDp(order, province, city, area, street,conditions);
			// 清空session验证码
			session.setAttribute("mobileValidateCode", null);
		} catch (Exception e) {
			logger.error("保存订单失败...", e);
			result.setResult(false);
			result.setErrorMsg("系统繁忙，请您稍后再试！");
			return result.toJson();
		}
		logger.info("End method add....");
		result.setResult(true);
		return result.toJson();
	}

	/**
	 * 支付宝付款则设置数据并跳转到付款页面
	 * @param order
	 * @param request
	 * @return
	 */
	private String sendZhifubao(Order order, HttpServletRequest request) {

		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_partner_trade_by_buyer");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		// 必填，不能修改
		sParaTemp.put("payment_type", "1");

		String contextPath = request.getContextPath();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		String notifyUrl = request.getScheme() + "://" + serverName + ":"
				+ serverPort + contextPath + "/order/notify/"
				+ order.getOuterid();

		String returnUrl = request.getScheme() + "://" + serverName + ":"
				+ serverPort + contextPath + "/order/orderSuccess/"
				+ order.getOuterid();
		// 异步通知地址
		sParaTemp.put("notify_url", notifyUrl);
		// 返回地址
		sParaTemp.put("return_url", returnUrl);
		// 卖家支付宝账号
		sParaTemp.put("seller_email", "shanqun017582@163.com");
		// 商户订单号
		sParaTemp.put("out_trade_no", order.getOuterid());
		// 订单名称
		sParaTemp.put("subject", "名鞋团购网");
		// TODO测试阶段价格默认写死为1元
		sParaTemp.put("price", String.valueOf(order.getTotalPrice()));
		// 商品数量
		sParaTemp.put("quantity", "1");
		// 物流费用
		sParaTemp.put("logistics_fee", "0.00");
		// 必填，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
		sParaTemp.put("logistics_type", "EXPRESS");
		// 物流支付方式
		// 必填，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
		sParaTemp.put("logistics_payment", "SELLER_PAY");
		// 订单描述
		sParaTemp.put("body", "");
		// 商品展示地址
		sParaTemp.put("show_url", "");
		// 收货人姓名
		sParaTemp.put("receive_name", order.getName());
		// 收货人地址
		sParaTemp.put("receive_address", order.getAddr());
		// 收货人邮编
		sParaTemp.put("receive_zip", "");
		// 收货人电话
		sParaTemp.put("receive_phone", "");
		// 收货人手机号码
		sParaTemp.put("receive_mobile", order.getMobile());

		// 建立请求
		String sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");

		return sHtmlText;
	}

	/**
	 * 获取购买的商品信息
	 * 
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<CartVO> getCarts(HttpSession session) {
		Map<String, CartVO> carts = null;
		List<CartVO> cartList = new ArrayList<CartVO>();
		if (null != session.getAttribute("carts")) {
			carts = (Map<String, CartVO>) session.getAttribute("carts");
			Set<Entry<String, CartVO>> entrySet = carts.entrySet();
			for (Entry<String, CartVO> entry : entrySet) {
				CartVO vo = entry.getValue();
				Goods goods = goodsService.get(vo.getGoodsId());
				vo.setGoods(goods);
				cartList.add(vo);
			}
		}
		return cartList;
	}

	/**
	 * 获取购买的商品信息
	 *
	 * @param session
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private Map<String,Object> getCartsByKeys(HttpSession session,String keys) {
		String[] keyStrs = keys.split(",");
		Map<String, CartVO> carts = null;
		List<CartVO> cartList = new ArrayList<CartVO>();
		Map<String, CartVO> surPluscarts = new HashMap<String, CartVO>();
		double totalPrice = 0.00;
		if (null != session.getAttribute("carts")) {
			carts = (Map<String, CartVO>) session.getAttribute("carts");
			Set<Entry<String, CartVO>> entrySet = carts.entrySet();
			for (Entry<String, CartVO> entry : entrySet) {
				CartVO cartVO = entry.getValue();
				//包含
				if(Arrays.asList(keyStrs).contains(entry.getKey())){
					ColorSizeItem colorSizeItem = colorSizeItemService.get(cartVO.getItemId());
					Goods goods = goodsService.get(cartVO.getGoodsId());
					totalPrice = totalPrice + BigDemicalUtil.mul(colorSizeItem.getPrice(), cartVO.getNum(),2);
					cartVO.setGoods(goods);
					cartList.add(cartVO);
				}else {
					surPluscarts.put(entry.getKey(),cartVO);
				}
			}
		}
		Map<String,Object> mp = new HashMap<String,Object>();
		mp.put("cartList",cartList);
		mp.put("surPluscarts",surPluscarts);
		mp.put("totalPrice",totalPrice);
		return mp;
	}

	@RequestMapping(value = "/pageListForCustomer.do", method = {RequestMethod.GET })
	@ResponseBody
	public String pageListForCustomer(OrderQueryVO orderVO, HttpSession session) {
		logger.info("Enter pageList ...,orderVO=" + orderVO);
		Result result = new Result();
		Page page = new Page();

		page.setCurrPage(orderVO.getCurrPage());
		Map<String, Object> conditions = new HashMap<String, Object>();

		// 如果用户登录了
		if (null != session.getAttribute("customer")) {
			Customer customer = (Customer) session.getAttribute("customer");
			conditions.put("customerId", customer.getId());
			// 用户未登录
		} else {
			conditions.put("customerId", "-1");
		}
		if (null != orderVO.getStatus()) {
			conditions.put("status", orderVO.getStatus());
		}

		if (!StringUtils.isEmpty(orderVO.getTitle())) {
			conditions.put("title", orderVO.getTitle().trim());
		}

		if (!StringUtils.isEmpty(orderVO.getName())) {
			conditions.put("name", orderVO.getName().trim());
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		List<Order> orderList = orderService.pageList(page, conditions);
		List<OrderTabVO> orderVOList = new ArrayList<OrderTabVO>();

		if (null != orderList) {
			for (Order order : orderList) {
				OrderTabVO vo = new OrderTabVO();
				vo.setOrder(order);
				List<CartVO> cartVOList = orderService.getCartVOList(order
						.getId());
				vo.setGoodsList(cartVOList);
				Date updateDate = order.getUpdateDate();
				String format = sdf.format(updateDate);
				vo.setUpdateDate(format);
				orderVOList.add(vo);
			}
		}
		int totalCount = orderService.totalCount(conditions);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalPage", page.getTotalPage());
		mp.put("totalCount", totalCount);
		mp.put("list", orderVOList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/orderSuccess/{outerid}", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String orderSuccess(@PathVariable String outerid, String trade_no,
			String trade_status, HttpServletRequest request) {
		request.setAttribute("outerid", outerid);
		Order order = orderService.getByOuterid(outerid);
		if (null != order) {
			order.setTradeNo(trade_no);
			order.setTradeStatus(trade_status);
			orderService.update(order);
		}
		return "orderSuccess";
	}
	
	@RequestMapping(value = "/porderSuccess/{outerid}", method = {
			RequestMethod.POST, RequestMethod.GET })
	public String porderSuccess(@PathVariable String outerid, String trade_no,
			String trade_status, HttpServletRequest request) {
		request.setAttribute("outerid", outerid);
		Order order = orderService.getByOuterid(outerid);
		if (null != order) {
			order.setTradeNo(trade_no);
			order.setTradeStatus(trade_status);
			orderService.update(order);
		}
		return "pc/porderSuccess";
	}

	@RequestMapping(value = "/notify/{outerid}", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String notify(@PathVariable String outerid, String trade_no,
			String trade_status, HttpServletRequest request) {
		request.setAttribute("outerid", outerid);
		logger.info("Enter method notify,outerid=" + outerid + ",trade_no="
				+ trade_no + ",trade_status=" + trade_status);
		try {
			Order order = orderService.getByOuterid(outerid);
			if (null != order) {
				order.setTradeNo(trade_no);
				order.setTradeStatus(trade_status);
				orderService.update(order);
			}
		} catch (Exception e) {
			logger.error("更新订单付款状态失败...", e);
			return "error";
		}
		return "success";
	}

	/**
	 * 用于顾客下单在订单列表中付款操作
	 * 
	 * @param outerid
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/pay.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String pay(String outerid, HttpServletRequest request) {
		logger.info("Enter method pay....，outerid=" + outerid);
		// 建立请求
		String sHtmlText;
		try {
			Order order = orderService.getByOuterid(outerid);
			// 把请求参数打包成数组
			Map<String, String> sParaTemp = new HashMap<String, String>();
			sParaTemp.put("service", "create_partner_trade_by_buyer");
			sParaTemp.put("partner", AlipayConfig.partner);
			sParaTemp.put("_input_charset", AlipayConfig.input_charset);
			// 必填，不能修改
			sParaTemp.put("payment_type", "1");
			String contextPath = request.getContextPath();
			String serverName = request.getServerName();
			int serverPort = request.getServerPort();
			String notifyUrl = request.getScheme() + "://" + serverName + ":"
					+ serverPort + contextPath + "/order/notify/"
					+ order.getOuterid();

			String returnUrl = request.getScheme() + "://" + serverName + ":"
					+ serverPort + contextPath + "/order/orderSuccess/"
					+ order.getOuterid();
			// 异步通知地址
			sParaTemp.put("notify_url", notifyUrl);
			// 返回地址
			sParaTemp.put("return_url", returnUrl);
			// 卖家支付宝账号
			sParaTemp.put("seller_email", "shanqun017582@163.com");
			// 商户订单号
			sParaTemp.put("out_trade_no", order.getOuterid());
			// 订单名称
			sParaTemp.put("subject", "名鞋团购网");
			sParaTemp.put("price", String.valueOf(order.getTotalPrice()));
			// 商品数量
			sParaTemp.put("quantity", "1");
			// 物流费用
			sParaTemp.put("logistics_fee", "0.00");
			// 必填，三个值可选：EXPRESS（快递）、POST（平邮）、EMS（EMS）
			sParaTemp.put("logistics_type", "EXPRESS");
			// 物流支付方式
			// 必填，两个值可选：SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
			sParaTemp.put("logistics_payment", "SELLER_PAY");
			// 订单描述
			sParaTemp.put("body", "");
			// 商品展示地址
			sParaTemp.put("show_url", "");
			// 收货人姓名
			sParaTemp.put("receive_name", order.getName());
			// 收货人地址
			sParaTemp.put("receive_address", order.getAddr());
			// 收货人邮编
			sParaTemp.put("receive_zip", "");
			// 收货人电话
			sParaTemp.put("receive_phone", "");
			// 收货人手机号码
			sParaTemp.put("receive_mobile", order.getMobile());
			sHtmlText = AlipaySubmit.buildRequest(sParaTemp, "get", "确认");
			return sHtmlText;
		} catch (Exception e) {
			logger.error("支付宝付款失败...", e);
		}

		return "调整到支付宝付款页面失败，请稍后再试！";

	}

	@RequestMapping(value = "/getWaitPayTotalCount.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String getWaitPayTotalCount(HttpSession session) {
		Result result = new Result();
		//判断用户是否登录
		Object obj = session.getAttribute("customer");
		if(null == obj){
			result.setResult(false);
			result.setErrorMsg("用户未登录！");
			return result.toJson();
		}
		try {
			Customer cus = (Customer)obj;
			Map<String,Object> contions = new HashMap<String, Object>();
			contions.put("customerId",cus.getId());
			int count = orderService.getWaitPayTotalCount(contions);
			result.setObj(count);
			result.setResult(true);
		}catch(Exception e){
			logger.error("数据库异常...,",e);
			result.setResult(false);
			result.setErrorMsg("操作失败！");
			return result.toJson();
		}
		return result.toJson();
	}

	//确认收货
	@RequestMapping(value = "/confirmTakeGoods.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String confirmTakeGoods(int id,HttpServletRequest req) {
		logger.info("Enter method memo....，id=" + id);
		Result result = new Result();
		HttpSession session = req.getSession();
		String ip = req.getRemoteAddr();
		logger.info("oper ip=" + ip);
		Customer customer = (Customer) session.getAttribute("customer");

		Order order = orderService.get(id);

		if(customer.getId() != order.getCustomerId()){
			result.setResult(false);
			result.setErrorMsg("您没有权限操作该订单");
			return result.toJson();
		}
		if (null != order) {
			order.setStatus(3);
			orderService.update(order);
		} else {
			result.setResult(false);
			logger.info("不存在该订单");
			result.setErrorMsg("不存在该订单");
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

}